package service

import (
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"github.com/jinzhu/copier"
	"go-demo/common/global"
	"go-demo/mvc/model"
	"time"
)

func GenerateJWT(userid uint) (string, error) {
	var (
		jwtKey = []byte(global.App.Config.JwtConfig.Secret)
		jwtTtl = global.App.Config.JwtConfig.JwtTtl
	)

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"userid": userid,
		"exp":    time.Now().Add(jwtTtl).Unix(),
	})
	return token.SignedString(jwtKey)
}

func loginUser(c *gin.Context) (model.UserVo, error) {
	userid := c.GetUint("userid")
	var user model.User
	user.ID = userid
	result := global.App.Mysql.First(&user)

	var userVO model.UserVo
	if result.Error != nil {
		copier.Copy(&userVO, &user)
		return userVO, result.Error
	}
	return userVO, nil
}
